"""
基于select 的IO多路复用并发网络模型
"""

from socket import *
from select import select

HOST = "0.0.0.0"
PORT = 8888
ADDR =(HOST,PORT)

#创建监听套接字
sock = socket()
sock.bind(ADDR)
sock.listen(5)
sock.setblocking(False)#设置为非阻塞IO

rlist = [sock]#初始关注为sock
wlsit = []
xlist = []


while True:
    try:
        rs,ws,xs = select(rlist,wlsit,xlist)
        for r in rs:
            if r is sock:
        #监听套接字读事件处理
                conn,addr = sock.accept()
                print("Connect from",addr)
                conn.setblocking(False)
                rlist.append(conn)
            else:
                #连接套接字读事件处理
                data = r.recv(1024)
                if not data:
                    rlist.remove(r)
                    r.close()
                    continue
                print(data.decode())
                r.send(b"OK")
        #         wlsit.append(r)
        # for w in ws:
        #     w.send(b"ok")
        #     wlsit.remove(w)
    except KeyboardInterrupt:
        break









